package com.heliang.util;

import java.io.File;
import java.util.List;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.widget.ImageView;
import com.heliang.common.FileIOUtil;
import com.heliang.common.ImageDispose;
import com.heliang.common.ImageUtil;
import com.heliang.util.AsyncImageLoader.ImageCallback;

public class ImageLoaderUtil {
	
	public static ImageLoaderUtil instance = new ImageLoaderUtil();
	private AsyncImageLoader asyncImageLoader;
	

	public ImageLoaderUtil() {
		// TODO Auto-generated constructor stub
		asyncImageLoader = new AsyncImageLoader();
	}
	
	/**
     * 图片回调（剪裁版本）
     */
    private AsyncImageLoader.ImageCallback imageCallback = new ImageCallback() {
    	@Override
        public void imageLoaded(String savePath,Drawable imageDrawable, List<ImageView> ivList) {
           
    		if (ivList == null) {
				return;
			}
    		
    		for (int i = 0; i < ivList.size(); i++) {
    			ImageView iv = (ImageView)ivList.get(i);
    			if (iv == null) {
					continue;
				}
    			
    			if (iv != null && imageDrawable != null ) { // 防止图片url获取不到图片是，占位图片不见了的情况
                	try {
                		Bitmap bitmapDes;
                		BitmapDrawable bd = (BitmapDrawable) imageDrawable;
                		Bitmap bitmap = bd.getBitmap();
                		float scale = calculateScale(bitmap.getWidth(), bitmap.getHeight(),
                				iv.getDrawable().getIntrinsicWidth(),iv.getDrawable().getIntrinsicHeight());
                		
                		if (bitmap.getWidth() == iv.getDrawable().getIntrinsicWidth() && bitmap.getHeight() == iv.getDrawable().getIntrinsicHeight()) {
                			bitmapDes = bitmap;
                		}else {
                			bitmapDes = ImageUtil.zoomImage(bitmap, scale);
                			int x = (bitmapDes.getWidth() - iv.getDrawable().getIntrinsicWidth())/2;
                			int y = (bitmapDes.getHeight() - iv.getDrawable().getIntrinsicHeight())/2;
                			
                			bitmapDes = Bitmap.createBitmap(bitmapDes, x, y, iv.getDrawable().getIntrinsicWidth(), iv.getDrawable().getIntrinsicHeight());
                		}
                    	
                    	iv.setImageBitmap(bitmapDes);
                    	
                    	File fileTmp = new File(savePath);
                    	if (!fileTmp.exists()) {
                    		FileIOUtil.saveImage(ImageDispose.Bitmap2Bytes(bitmapDes), savePath);//保存已经裁剪的图片
    					}
                		
//                		iv.setImageDrawable(imageDrawable);
    				} catch (Exception e) {
    					// TODO: handle exception
    					Log.e(Constants.TAG, e.getMessage());
    				}
                	
                }
			}
    		
        }
    };
    
    /**
     * 图片回调（剪裁版本）
     */
   /* private AsyncImageLoader.ImageCallback imageZoomCallback = new ImageCallback() {
    	@Override
        public void imageLoaded(String savePath,Drawable imageDrawable, ImageView iv) {
//            ImageView imageViewByTag = (ImageView) listView.findViewWithTag(imageUrl);
//            Log.i("test", "Drawable cachedImage = asyncImageLoader.loadDrawable( )-->");
            if (iv != null && imageDrawable != null ) { // 防止图片url获取不到图片是，占位图片不见了的情况
            	try {
            		Bitmap bitmapDes;
            		BitmapDrawable bd = (BitmapDrawable) imageDrawable;
            		Bitmap bitmap = bd.getBitmap();
                	float scale = calculateScale(bitmap.getWidth(), bitmap.getHeight(),
            				iv.getDrawable().getIntrinsicWidth(),iv.getDrawable().getIntrinsicHeight());
            		
                	if (scale == 1) {
                		bitmapDes = bitmap;
					}else {
						bitmapDes = ImageUtil.zoomImage(bitmap, scale);
//	            		int x = (bitmapDes.getWidth() - iv.getDrawable().getIntrinsicWidth())/2;
//	            		int y = (bitmapDes.getHeight() - iv.getDrawable().getIntrinsicHeight())/2;
//	            		
//	            		bitmapDes = Bitmap.createBitmap(bitmapDes, x, y, iv.getDrawable().getIntrinsicWidth(), iv.getDrawable().getIntrinsicHeight());
					}
                	
                	File fileTmp = new File(savePath);
                	if (!fileTmp.exists()) {
                		FileIOUtil.saveImage(ImageDispose.Bitmap2Bytes(bitmapDes), savePath);//保存已经裁剪的图片
					}
            		
            		
            		iv.setImageBitmap(bitmapDes);
//            		iv.setImageDrawable(imageDrawable);
				} catch (Exception e) {
					// TODO: handle exception
					Log.e(Constants.TAG, e.getMessage());
				}
            	
            }
        }
    };*/
    
    /**
     * 图片回调（保存不裁剪版本）
     */
    private AsyncImageLoader.ImageCallback imageCallbackNoCut = new ImageCallback() {
    	@Override
        public void imageLoaded(String savePath,Drawable imageDrawable, List<ImageView> ivList) {
//            ImageView imageViewByTag = (ImageView) listView.findViewWithTag(imageUrl);
//            Log.i("test", "Drawable cachedImage = asyncImageLoader.loadDrawable( )-->");
            
    		if(ivList == null || ivList.size() <= 0){
    			return;
    		}
    		
    		for (int i = 0; i < ivList.size(); i++) {
    			ImageView iv = (ImageView)ivList.get(i);
    			
    			if (iv == null) {
                	continue;
    			}
    			if (iv != null && imageDrawable != null ) { // 防止图片url获取不到图片是，占位图片不见了的情况
                	try {
                		Bitmap bitmapDes;
                		BitmapDrawable bd = (BitmapDrawable) imageDrawable;
                		Bitmap bitmap = bd.getBitmap();
                    	float scale = calculateScale(bitmap.getWidth(), bitmap.getHeight(),
                				iv.getDrawable().getIntrinsicWidth(),iv.getDrawable().getIntrinsicHeight());
                		
                    	
                    	File fileTmp = new File(savePath);
                    	if (!fileTmp.exists()) {
                    		FileIOUtil.saveImage(ImageDispose.Bitmap2Bytes(bitmap), savePath);//保存已经裁剪的图片
    					}
                    	
                    	if (scale == 1) {
                    		bitmapDes = bitmap;
    					}else {
    						bitmapDes = ImageUtil.zoomImage(bitmap, scale);
    	            		int x = (bitmapDes.getWidth() - iv.getDrawable().getIntrinsicWidth())/2;
    	            		int y = (bitmapDes.getHeight() - iv.getDrawable().getIntrinsicHeight())/2;
    	            		
    	            		bitmapDes = Bitmap.createBitmap(bitmapDes, x, y, iv.getDrawable().getIntrinsicWidth(), iv.getDrawable().getIntrinsicHeight());
    					}
                    	
                		iv.setImageBitmap(bitmapDes);
//                		iv.setImageDrawable(imageDrawable);
    				} catch (Exception e) {
    					// TODO: handle exception
    					Log.e(Constants.TAG, e.getMessage());
    				}
                	
                }
    			
    		}
        }
    };
    
   
    
    /**
     * 设置需要异步加载的图片
     */
    public ImageView setImageDrawable(String imagePath,String imageUrl,ImageView iv,boolean checkContain){
    	return asyncImageLoader.loadDrawable(imagePath, imageUrl,iv, imageCallback,checkContain);
    }
    
    /**
     * 设置需要异步加载的图片，需要缩放
     */
    public ImageView setImageDrawableZoom(String imagePath,String imageUrl,ImageView iv,boolean checkContain){
    	return asyncImageLoader.loadDrawable(imagePath, imageUrl,iv, imageCallback,checkContain);
    }
    
    /**
     * 设置需要异步加载的图片，不需要裁减缩放
     */
    public ImageView setImageDrawableNoCut(String imagePath,String imageUrl,ImageView iv,ImageCallback imageCallbackNoCut,boolean checkContain){
    	return asyncImageLoader.loadDrawable(imagePath, imageUrl,iv, imageCallbackNoCut,checkContain);
    	
    }
    
    /**
     * 设置需要异步加载的图片,不需要裁减缩放
     */
    public ImageView setImageDrawableSaveNoCut(String imagePath,String imageUrl,ImageView iv,boolean checkContain){
    	return asyncImageLoader.loadDrawable(imagePath, imageUrl,iv, imageCallbackNoCut,checkContain);
    	
    }
    
    
    /**
	 * 算出需要缩放的比例
	 * @param width
	 * @param height
	 * @return
	 */
	public static float calculateScale(int widthOrg,int heightOrg,int widthDes,int heightDes){
		float widthScale = (float)widthDes/widthOrg;
		float heightScale = (float)heightDes/heightOrg;
		return widthScale < heightScale?heightScale:widthScale;
	}

}
